<!doctype html>




<html class="theme-next pisces" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
    
  
  <link href="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic|Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="算法," />





  <link rel="alternate" href="/atom.xml" title="不知归期的故人" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/images/favicon.ico?v=5.1.0" />






<meta name="description" content="排序（一）基础排序算法冒泡排序时间复杂度为O(N2) 过程:  循环空间为0到N-1，第一个数和第二个数比较，较大的放在后面，第二个和第三个数比较，较大的放在后面，一直循环到最后，最大的数放在最后面N-1位置。 循环空间为0到N-2，依次比较相邻的数，最大的数放在N-2位置。 循环空间为0到1，最大的数放在1位置。">
<meta name="keywords" content="算法">
<meta property="og:type" content="article">
<meta property="og:title" content="[牛客网算法]--排序">
<meta property="og:url" content="https://kusole.github.io/2018/04/18/NCsort/index.html">
<meta property="og:site_name" content="不知归期的故人">
<meta property="og:description" content="排序（一）基础排序算法冒泡排序时间复杂度为O(N2) 过程:  循环空间为0到N-1，第一个数和第二个数比较，较大的放在后面，第二个和第三个数比较，较大的放在后面，一直循环到最后，最大的数放在最后面N-1位置。 循环空间为0到N-2，依次比较相邻的数，最大的数放在N-2位置。 循环空间为0到1，最大的数放在1位置。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://kusole.github.io/2018/04/18/NCsort/1523275715688.png">
<meta property="og:image" content="https://kusole.github.io/2018/04/18/NCsort/1523275946885.png">
<meta property="og:updated_time" content="2019-02-26T08:30:08.246Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="[牛客网算法]--排序">
<meta name="twitter:description" content="排序（一）基础排序算法冒泡排序时间复杂度为O(N2) 过程:  循环空间为0到N-1，第一个数和第二个数比较，较大的放在后面，第二个和第三个数比较，较大的放在后面，一直循环到最后，最大的数放在最后面N-1位置。 循环空间为0到N-2，依次比较相邻的数，最大的数放在N-2位置。 循环空间为0到1，最大的数放在1位置。">
<meta name="twitter:image" content="https://kusole.github.io/2018/04/18/NCsort/1523275715688.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: false,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://kusole.github.io/2018/04/18/NCsort/"/>





  <title> [牛客网算法]--排序 | 不知归期的故人 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?124e5902fa6b3c1d89682ed1fa0441ac";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">不知归期的故人</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">乘风破浪会有时，直挂云帆济沧海。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocapitalize="off" autocomplete="off" autocorrect="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://kusole.github.io/2018/04/18/NCsort/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="刘韬">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="不知归期的故人">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                [牛客网算法]--排序
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-04-18T16:39:47+08:00">
                2018-04-18
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/工作面试/" itemprop="url" rel="index">
                    <span itemprop="name">工作面试</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="排序（一）基础排序算法"><a href="#排序（一）基础排序算法" class="headerlink" title="排序（一）基础排序算法"></a>排序（一）基础排序算法</h1><h2 id="冒泡排序"><a href="#冒泡排序" class="headerlink" title="冒泡排序"></a>冒泡排序</h2><p>时间复杂度为O(N2)</p>
<p>过程:</p>
<ul>
<li>循环空间为0到N-1，第一个数和第二个数比较，较大的放在后面，第二个和第三个数比较，较大的放在后面，一直循环到最后，最大的数放在最后面N-1位置。</li>
<li>循环空间为0到N-2，依次比较相邻的数，最大的数放在N-2位置。</li>
<li>循环空间为0到1，最大的数放在1位置。</li>
</ul>
<a id="more"></a>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BubbleSort</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">int</span>* <span class="title">bubbleSort</span><span class="params">(<span class="keyword">int</span>* A, <span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// write code here</span></span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i=n<span class="number">-1</span>;i&gt;=<span class="number">1</span>;i--)&#123;</span><br><span class="line">            <span class="keyword">for</span>(<span class="keyword">int</span> j=<span class="number">0</span>;j&lt;i;j++)&#123;</span><br><span class="line">                <span class="keyword">if</span>(A[j]&gt;A[j+<span class="number">1</span>])&#123;</span><br><span class="line">                    <span class="keyword">int</span> t = A[j];</span><br><span class="line">                    A[j]=A[j+<span class="number">1</span>];</span><br><span class="line">                    A[j+<span class="number">1</span>]=t;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> A;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<h2 id="选择排序"><a href="#选择排序" class="headerlink" title="选择排序"></a>选择排序</h2><p>时间复杂度为O(N2)</p>
<p>过程：</p>
<ul>
<li>循环空间为0到N-1，选择最小的和0位置交换</li>
<li>循环空间为1到N-1, 选择最小的和1位置交换</li>
<li>循环空间为N-2到N-1，选择最小的和N-2交换<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SelectionSort</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">int</span>* <span class="title">selectionSort</span><span class="params">(<span class="keyword">int</span>* A, <span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// write code here</span></span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;n<span class="number">-1</span>;i++)&#123;</span><br><span class="line">            <span class="keyword">int</span> min = i;</span><br><span class="line">            <span class="keyword">for</span>(<span class="keyword">int</span> j=i+<span class="number">1</span>;j&lt;n;j++)&#123;</span><br><span class="line">                <span class="keyword">if</span>(A[j]&lt;=A[min])min=j;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">int</span> t = A[i];</span><br><span class="line">            A[i]=A[min];</span><br><span class="line">            A[min]=t;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> A;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="插入排序"><a href="#插入排序" class="headerlink" title="插入排序"></a>插入排序</h2><p>时间复杂度为O(N2)</p>
<p>过程：</p>
<ul>
<li>循环空间为0-1，如果位置1上的数小于位置0上的数，交换</li>
<li>循环空间为0-2，如果位置2上的数小于前面位置的数，前面位置的数往后移动</li>
<li>循环空间为0-N-1，如果位置N上的数小于前面的数，前面位置的数往后移动</li>
<li>直到前面的数小于等于当前比较的数，这个数就插入该位置，后面的数往后移<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">InsertionSort</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">int</span>* <span class="title">insertionSort</span><span class="params">(<span class="keyword">int</span>* A, <span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// write code here</span></span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">1</span>;i&lt;=n<span class="number">-1</span>;i++)&#123;</span><br><span class="line">            <span class="keyword">int</span> k = A[i];</span><br><span class="line">            <span class="keyword">int</span> j;</span><br><span class="line">            <span class="keyword">for</span>(j=i<span class="number">-1</span>;j&gt;=<span class="number">0</span>;j--)&#123;</span><br><span class="line">                <span class="keyword">if</span>(A[j]&gt;=k)A[j+<span class="number">1</span>]=A[j];</span><br><span class="line">                <span class="keyword">else</span> <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            A[j+<span class="number">1</span>]=k;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> A;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="归并排序"><a href="#归并排序" class="headerlink" title="归并排序"></a>归并排序</h2><p>时间复杂度为O(N*logN)</p>
<p>过程：</p>
<ul>
<li>数组的每一个数变成长度为1的有序空间，把相邻的组进行合并，得到最大长度为2的有序区间</li>
<li>将长度为2的有序区间进行合并，得到最大长度为4的有序区间</li>
<li>一直进行下去，直到得到只有一个有序区间停止<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MergeSort</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">int</span> *<span class="title">mergeSort</span><span class="params">(<span class="keyword">int</span> *A, <span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// write code here</span></span><br><span class="line">        mergeSort1(A,<span class="number">0</span>,n<span class="number">-1</span>);</span><br><span class="line">        <span class="keyword">return</span> A;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">Merge</span><span class="params">(<span class="keyword">int</span> *A, <span class="keyword">int</span> low, <span class="keyword">int</span> mid, <span class="keyword">int</span> high)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> i = low;</span><br><span class="line">        <span class="keyword">int</span> j = mid + <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">int</span> k = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">int</span> *B = <span class="keyword">new</span> <span class="keyword">int</span>[high - low + <span class="number">1</span>];</span><br><span class="line"></span><br><span class="line">        <span class="keyword">while</span> (i &lt;= mid &amp;&amp; j &lt;= high) &#123;</span><br><span class="line">            <span class="keyword">if</span> (A[i] &lt;= A[j]) &#123;</span><br><span class="line">                B[k++] = A[i++];</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                B[k++] = A[j++];</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">while</span> (i &lt;= mid) &#123;</span><br><span class="line">            B[k++] = A[i++];</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">while</span> (j &lt;= high) &#123;</span><br><span class="line">            B[k++] = A[j++];</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">for</span> (k = <span class="number">0</span>, i = low; i &lt;= high; i++, k++) &#123;</span><br><span class="line">            A[i] = B[k];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">mergeSort1</span><span class="params">(<span class="keyword">int</span> *A, <span class="keyword">int</span> low, <span class="keyword">int</span> high)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (low &gt;= high)<span class="keyword">return</span>;</span><br><span class="line">        <span class="keyword">int</span> mid = (low + high) / <span class="number">2</span>;</span><br><span class="line">        mergeSort1(A, low, mid);</span><br><span class="line">        mergeSort1(A, mid + <span class="number">1</span>, high);</span><br><span class="line">        Merge(A, low, mid, high);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="快速排序"><a href="#快速排序" class="headerlink" title="快速排序"></a>快速排序</h2><p>时间复杂度为O(N*logN)</p>
<p>过程：</p>
<ul>
<li>随机的在数组中选择一个数，将小于等于该数的放在这个数的前面，大于该数的放在该数的后面</li>
<li>左边选出的数和右边选出的数又随机选择一个数，依次递归调用上述过程</li>
</ul>
<p>完整划分过程（时间复杂度为O(N)）：</p>
<ul>
<li>将划分值和最后一个元素交换，设定划分区间为-1</li>
<li>依次遍历，如果当前元素大于划分值，比较下一个元素</li>
<li>如果当前元素小于划分值，将该元素和划分区间+1的位置元素交换，然后将划分区间值加1</li>
<li>直到便利完一遍后，没有发现比划分值小的，将划分值和划分区间值的后一个位置值交换<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">QuickSort</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">int</span> *<span class="title">quickSort</span><span class="params">(<span class="keyword">int</span> *A, <span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// write code here</span></span><br><span class="line">        qSort(A,<span class="number">0</span>,n<span class="number">-1</span>);</span><br><span class="line">        <span class="keyword">return</span> A;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">partion</span><span class="params">(<span class="keyword">int</span> *A, <span class="keyword">int</span> low, <span class="keyword">int</span> high)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> div = low - <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">int</span> t;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = low; i &lt; high; i++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (A[i] &lt;= A[high]) &#123;</span><br><span class="line">                t = A[div + <span class="number">1</span>];</span><br><span class="line">                A[div + <span class="number">1</span>] = A[i];</span><br><span class="line">                A[i] = t;</span><br><span class="line">                div++;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        t = A[div + <span class="number">1</span>];</span><br><span class="line">        A[div + <span class="number">1</span>] = A[high];</span><br><span class="line">        A[high] = t;</span><br><span class="line">        <span class="keyword">return</span> div+<span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">qSort</span><span class="params">(<span class="keyword">int</span> *A, <span class="keyword">int</span> low, <span class="keyword">int</span> high)</span></span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(low&gt;=high)<span class="keyword">return</span>;</span><br><span class="line">        <span class="keyword">int</span> p=partion(A,low,high);</span><br><span class="line">        qSort(A,low,p<span class="number">-1</span>);</span><br><span class="line">        qSort(A,p+<span class="number">1</span>,high);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="堆排序"><a href="#堆排序" class="headerlink" title="堆排序"></a>堆排序</h2><p>时间复杂度为O(N*logN)</p>
<p>过程：</p>
<ul>
<li>将数组中的N个数建立成为大小为N的大根堆</li>
<li>将堆顶的值和堆最后一个值交换，选出最大值，将此值剔除该堆，放在数组位置N</li>
<li>将大小为N-1的堆进行大根堆的调整，将N-1数中的最大值放在堆顶的位置，将堆顶的位置和堆最后一个元素交换，将此值剔除该堆，放在数组位置N-1</li>
<li>循环直到剩下最后一个元素</li>
</ul>
<h2 id="希尔排序"><a href="#希尔排序" class="headerlink" title="希尔排序"></a>希尔排序</h2><p>时间复杂度为O(N*logN)</p>
<p>过程：</p>
<ul>
<li>设定步长为3</li>
<li>比较位置3的数和位置3-3的数，如果小，则交换，再比较0-3&lt;0，下一步</li>
<li>比较位置4的数和位置4-3的数，如果小，则交换，再比较1-3&lt;0，下一步</li>
<li>比较位置5的数和位置5-3的数，如果小，则交换，再比较2-3&lt;0，下一步</li>
<li>比较位置5的数和位置6-3的数，如果小，则交换，再比较3-3=0，比较6-3和位置6-3-3的值，如果小，则交换，依次进行上述比较</li>
<li>设定步长为2，过程类似</li>
<li>设定步长为1，过程类似，结束排序<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ShellSort</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">int</span> *<span class="title">shellSort</span><span class="params">(<span class="keyword">int</span> *A, <span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// write code here</span></span><br><span class="line">        <span class="keyword">int</span> gap = n / <span class="number">2</span>;</span><br><span class="line">        <span class="keyword">while</span> (gap &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = gap; i &lt; n; i++) &#123;</span><br><span class="line">                <span class="keyword">for</span> (<span class="keyword">int</span> j = i - gap; j &gt;= <span class="number">0</span>; j -= gap) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (A[j] &gt; A[j + gap]) &#123;</span><br><span class="line">                        <span class="keyword">int</span> t = A[j];</span><br><span class="line">                        A[j] = A[j + gap];</span><br><span class="line">                        A[j + gap] = t;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            gap = gap / <span class="number">2</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> A;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h1 id="排序（二）计数排序算法"><a href="#排序（二）计数排序算法" class="headerlink" title="排序（二）计数排序算法"></a>排序（二）计数排序算法</h1><h2 id="计数排序和基数排序"><a href="#计数排序和基数排序" class="headerlink" title="计数排序和基数排序"></a>计数排序和基数排序</h2><p>不是基于比较的排序，思想来源于桶排序，有计数排序和基数排序。</p>
<h3 id="计数排序"><a href="#计数排序" class="headerlink" title="计数排序"></a>计数排序</h3><p><code>原理</code>：<br>计数排序非常基础，他的主要目的是对整数排序并且会比普通的排序算法性能更好。例如，输入{1, 3, 5, 2, 1, 4}给计数排序，会输出{1, 1, 2, 3, 4, 5}。这个算法由以下步骤组成：</p>
<ul>
<li>初始化一个计数数组，大小是输入数组中的最大的数。</li>
<li>遍历输入数组，遇到一个数就在计数数组对应的位置上加一。例如：遇到5，就将计数数组第五个位置的数加一。</li>
<li>把计数数组直接覆盖到输出数组（节约空间）。</li>
</ul>
<p><code>例子</code>:<br>输入{3, 4, 3, 2, 1}，最大是4，数组长度是5。<br>建立计数数组{0, 0, 0, 0}。<br>遍历输入数组：<br>{<strong>3</strong>, 4, 3, 2, 1} -&gt; {0, 0, 1, 0}<br>{3, <strong>4</strong>, 3, 2, 1} -&gt; {0, 0, 1, 1}<br>{3, 4, <strong>3</strong>, 2, 1} -&gt; {0, 0, 2, 1}<br>{3, 4, 3, <strong>2</strong>, 1} -&gt; {0, 1, 2, 1}<br>{3, 4, 3, 2, <strong>1</strong>} -&gt; {1, 1, 2, 1}  </p>
<p>计数数组现在是{1, 1, 2, 1}，我们现在把它写回到输入数组里：<br>{0, 1, 2, 1} -&gt; {1, 4, 3, 2, 1}<br>{0, 0, 2, 1} -&gt; {1, 2, 3, 2, 1}<br>{0, 0, 1, 1} -&gt; {1, 2, 3, 2, 1}<br>{0, 0, 0, 1} -&gt; {1, 2, 3, 3, 1}<br>{0, 0, 0, 0} -&gt; {1, 2, 3, 3, 4}</p>
<p>这样就排好序了。</p>
<ul>
<li>时间：O(n + k)，n是输入数组长度，k是最大的数的大小。</li>
<li>空间：O(n + k)，n是输入数组长度，k是最大的数的大小。</li>
</ul>
<p><code>代码</code>:<br><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">CountingSort</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">int</span> *<span class="title">countingSort</span><span class="params">(<span class="keyword">int</span> *A, <span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// write code here</span></span><br><span class="line">        <span class="keyword">int</span> i, j, num = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">int</span> max = <span class="number">0</span>, min = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; n; i++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (A[i] &gt; A[max])max = i;</span><br><span class="line">            <span class="keyword">if</span> (A[i] &lt; A[min])min = i;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">int</span> countmax = A[max];</span><br><span class="line">        <span class="keyword">int</span> countmin = A[min];</span><br><span class="line">        <span class="keyword">int</span> countarray[countmax - countmin + <span class="number">1</span>];</span><br><span class="line">        <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; countmax - countmin + <span class="number">1</span>; i++) &#123;</span><br><span class="line">            countarray[i]=<span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">            countarray[A[i]  - countmin]++;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; countmax - countmin + <span class="number">1</span>; i++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (countarray[i] &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="keyword">for</span> (j = <span class="number">0</span>; j &lt; countarray[i]; j++) &#123;</span><br><span class="line">                    A[num++] = i  + countmin;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> A;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<h1 id="排序（三）习题"><a href="#排序（三）习题" class="headerlink" title="排序（三）习题"></a>排序（三）习题</h1><h2 id="小范围排序"><a href="#小范围排序" class="headerlink" title="小范围排序"></a>小范围排序</h2><p><code>题目</code><br>已知一个几乎有序的数组，几乎有序是指，如果把数组排好序，每个元素的移动距离不超过k，并且k相对于数组长度来说很小，用什么排序发比较好？</p>
<ul>
<li>时间复杂度为o(n)的排序算法基数排序和基数排序，不知道数组的范围，因此不做考虑。</li>
<li>时间复杂度为o(n2)的排序算法冒泡排序和选择排序，与原始数组无关；插入排序与原始数据有关，对于本题，插入排序的时间复杂度为o(n*k)；</li>
<li>时间复杂度为o(n*logn)的排序算法，快速排序，归并排序与原始无关。</li>
<li>解决方法为改进后的堆排序。</li>
</ul>
<p><code>过程</code></p>
<p><img src="/2018/04/18/NCsort/1523275715688.png" alt="Alt text"></p>
<p>数组排序完毕，每得到一个数，代价为o(logk)，总共有n个数，时间复杂度为o(n*logk)。</p>
<h2 id="重复值判断"><a href="#重复值判断" class="headerlink" title="重复值判断"></a>重复值判断</h2><p><code>题目</code><br>判断数组中是否有重复值，必须保证额外空间复杂度为o(1)。</p>
<ul>
<li>如果没有空间限制，可以使用哈希表来做，统计是否有重复值。</li>
<li>先排序，然后遍历一遍之后看是否有相同的值</li>
</ul>
<p>考虑经典排序算法，空间复杂度限制。</p>
<p><img src="/2018/04/18/NCsort/1523275946885.png" alt="Alt text"></p>
<p><code>代码</code></p>
<h3 id="使用hash表方法代码如下"><a href="#使用hash表方法代码如下" class="headerlink" title="使用hash表方法代码如下"></a>使用hash表方法代码如下</h3><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Checker</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">bool</span> <span class="title">checkDuplicate</span><span class="params">(<span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt; a, <span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// write code here</span></span><br><span class="line">        <span class="keyword">if</span>(n&lt;<span class="number">2</span>) <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">        <span class="keyword">auto</span> ret = <span class="built_in">std</span>::minmax_element(a.begin(),a.end());</span><br><span class="line">        <span class="keyword">int</span> min = *ret.first;</span><br><span class="line">        <span class="keyword">int</span> max = *ret.second;</span><br><span class="line">        <span class="built_in">vector</span>&lt;<span class="keyword">size_t</span>&gt; <span class="built_in">map</span>(max-min+<span class="number">1</span>,<span class="number">0</span>);</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">auto</span> x:a)&#123;</span><br><span class="line">            <span class="keyword">if</span>(++<span class="built_in">map</span>[x-min]&gt;<span class="number">1</span>)<span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<h3 id="使用堆排序方法代码如下"><a href="#使用堆排序方法代码如下" class="headerlink" title="使用堆排序方法代码如下"></a>使用堆排序方法代码如下</h3><p>堆排序为大部分为递归实现，因此需要改为非递归版本的堆排序。</p>
<h2 id="有序数组合并"><a href="#有序数组合并" class="headerlink" title="有序数组合并"></a>有序数组合并</h2><p><code>题目</code><br>把两个有序数组合并为一个数组，第一个数组的空间正好可以容纳两个数组的元素。<br>数组A:2 4 6_ _ _<br>数组B:1 3 5<br><code>过程</code></p>
<ul>
<li>从后向前覆盖，比较6和5，将6放入最后一个位置。</li>
<li>再比较4和5，将5放入6之前。</li>
<li>依次比较，直到数组B全部复制到数组A中。</li>
</ul>
<p><code>代码</code><br><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Merge</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">int</span>* <span class="title">mergeAB</span><span class="params">(<span class="keyword">int</span>* A, <span class="keyword">int</span>* B, <span class="keyword">int</span> n, <span class="keyword">int</span> m)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// write code here</span></span><br><span class="line">        <span class="keyword">int</span> k = m + n<span class="number">-1</span>;</span><br><span class="line">        <span class="keyword">int</span> i = n<span class="number">-1</span>;</span><br><span class="line">        <span class="keyword">int</span> j = m<span class="number">-1</span>;</span><br><span class="line">        <span class="keyword">while</span>(i&gt;=<span class="number">0</span>&amp;&amp;j&gt;=<span class="number">0</span>)&#123;</span><br><span class="line">            <span class="keyword">if</span>(A[i]&gt;=B[j])&#123;</span><br><span class="line">                A[k--]=A[i--];</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span>&#123;</span><br><span class="line">                A[k--]=B[j--];</span><br><span class="line">            &#125;</span><br><span class="line">            </span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">while</span>(j&gt;=<span class="number">0</span>)&#123;</span><br><span class="line">            A[k--]=B[j--];</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> A;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<h2 id="三色排序-荷兰国旗"><a href="#三色排序-荷兰国旗" class="headerlink" title="三色排序/荷兰国旗"></a>三色排序/荷兰国旗</h2><p><code>题目</code><br>题目有一个只由0，1，2三种元素构成的整数数组，请使用交换、原地排序而不是使用计数进行排序。<br>给定一个只含0，1，2的整数数组A及它的大小，请返回排序后的数组。保证数组大小小于等于500。</p>
<blockquote>
<p>输入：[0,1,1,0,2,2],6<br>返回：[0,0,1,1,2,2]</p>
</blockquote>
<p><code>过程</code></p>
<ul>
<li>设置一个0区间，指向位置-1；设置一个2区间指向位置n；</li>
<li>从0位置开始遍历，如果遇到1，则跳到下一位置</li>
<li>如果遇到0，则将0和0区间的下一位置的数交换，跳到下一位置；</li>
<li>如果遇到2，则将2和2区间的前一位置的数交换，因为交换的数没有被遍历过，所以从当前位置开始判断；</li>
<li>直到遍历位置和2区间位置相等，结束遍历。</li>
</ul>
<p><code>代码</code><br><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ThreeColor</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt; sortThreeColor(<span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt; A, <span class="keyword">int</span> n) &#123;</span><br><span class="line">        <span class="comment">// write code here</span></span><br><span class="line">        <span class="keyword">int</span> begin = <span class="number">-1</span>;</span><br><span class="line">        <span class="keyword">int</span> end = n;</span><br><span class="line">        <span class="keyword">int</span> t;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;end;i++)&#123;</span><br><span class="line">            <span class="keyword">if</span>(A[i]==<span class="number">0</span>)&#123;</span><br><span class="line">                begin++;</span><br><span class="line">                t = A[begin];</span><br><span class="line">                A[begin] = A[i];</span><br><span class="line">                A[i] = t;</span><br><span class="line">                </span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span>(A[i]==<span class="number">2</span>)&#123;</span><br><span class="line">                end--;</span><br><span class="line">                t = A[end];</span><br><span class="line">                A[end] = A[i];</span><br><span class="line">                A[i] = t;</span><br><span class="line">                i--;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> A;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<h2 id="有序矩阵查找问题"><a href="#有序矩阵查找问题" class="headerlink" title="有序矩阵查找问题"></a>有序矩阵查找问题</h2><p><code>题目</code><br>现在有一个行和列都排好序的矩阵，请设计一个高效算法，快速查找矩阵中是否含有值x。<br>给定一个int矩阵mat，同时给定矩阵大小nxm及待查找的数x，请返回一个bool值，代表矩阵中是否存在x。所有矩阵中数字及x均为int范围内整数。保证n和m均小于等于1000。</p>
<blockquote>
<p>输入：[[1,2,3],[4,5,6],[7,8,9]],3,3,10<br>返回：false</p>
</blockquote>
<p><code>过程</code></p>
<ul>
<li>从矩阵的右上角开始查找，即位置[0][m-1]，col=0，row=m-1；</li>
<li>当遍历的数大于需要查找的数的时候，这个数列的下方所有的数都大于需要查找的数，此时应该row–；</li>
<li>当遍历的数小于需要查找的数的时候，这个数行的左边所有的数都小于需要查找的数，此时应该col++;</li>
<li>如果找到此数，则返回true；如果没有找到，则返回false；</li>
</ul>
<p><code>代码</code><br><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Finder</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">bool</span> <span class="title">findX</span><span class="params">(<span class="built_in">vector</span>&lt;<span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt; &gt; mat, <span class="keyword">int</span> n, <span class="keyword">int</span> m, <span class="keyword">int</span> x)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// write code here</span></span><br><span class="line">        <span class="keyword">if</span>(m &lt;= <span class="number">0</span> || n &lt;= <span class="number">0</span>)&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">int</span> col=<span class="number">0</span>,row=m<span class="number">-1</span>;</span><br><span class="line">        <span class="keyword">while</span>(col&lt;n&amp;&amp;row&gt;=<span class="number">0</span>)&#123;</span><br><span class="line">            <span class="keyword">if</span>(mat[col][row]&gt;x)row--;</span><br><span class="line">            <span class="keyword">else</span> <span class="keyword">if</span>(mat[col][row]&lt;x)col++;</span><br><span class="line">            <span class="keyword">else</span> <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<h2 id="最短子数组"><a href="#最短子数组" class="headerlink" title="最短子数组"></a>最短子数组</h2><p><code>题目</code><br>对于一个数组，请设计一个高效算法计算需要排序的最短子数组的长度。<br>给定一个int数组A和数组的大小n，请返回一个二元组，代表所求序列的长度。(原序列位置从0开始标号,若原序列有序，返回0)。保证A中元素均为正整数。</p>
<blockquote>
<p>输入：[1,4,6,5,9,10],6<br>返回：2</p>
</blockquote>
<p><code>过程</code></p>
<ul>
<li>从左向右遍历，选择当前遍历阶段的最大值，如果遇到比最大值小的，记录下来为maxindex；</li>
<li>从右向左遍历，选择当前遍历阶段的最小值，如果遇到比最小值大的，记录下来为minindex；</li>
<li>如果maxindex-minindex&lt;0，返回0，否则返回maxindex-minindex；</li>
</ul>
<p><code>代码</code><br><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Subsequence</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">shortestSubsequence</span><span class="params">(<span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt; A, <span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// write code here</span></span><br><span class="line">        <span class="keyword">int</span> maxindex = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">int</span> minindex = n<span class="number">-1</span>;</span><br><span class="line">        <span class="keyword">int</span> max=A[<span class="number">0</span>];</span><br><span class="line">        <span class="keyword">int</span> min=A[n<span class="number">-1</span>];</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i =<span class="number">0</span>;i&lt;n;i++)&#123;</span><br><span class="line">            <span class="keyword">if</span>(max&lt;=A[i])&#123;</span><br><span class="line">                max=A[i];</span><br><span class="line">            &#125;<span class="keyword">else</span> maxindex = i;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> j = n<span class="number">-1</span>;j&gt;=<span class="number">0</span>;j--)&#123;</span><br><span class="line">            <span class="keyword">if</span>(min&gt;=A[j])&#123;</span><br><span class="line">                min = A[j];</span><br><span class="line">            &#125;<span class="keyword">else</span> minindex = j;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> maxindex&gt;minindex?maxindex-minindex+<span class="number">1</span>:<span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<h2 id="相邻两数最大差值"><a href="#相邻两数最大差值" class="headerlink" title="相邻两数最大差值"></a>相邻两数最大差值</h2><p><code>题目</code><br>有一个整形数组A，请设计一个复杂度为O(n)的算法，算出排序后相邻两数的最大差值。<br>给定一个int数组A和A的大小n，请返回最大的差值。保证数组元素多于1个。</p>
<blockquote>
<p>输入：[1,2,5,4,6],5<br>返回：2</p>
</blockquote>
<p><code>过程</code></p>
<ul>
<li>求出数组的最大值valueMax，最小值valueMin；</li>
<li>初始化设定两个桶bocketMax，bocketMin；初始化为INT_MIN和INT_MAX；</li>
<li>确定桶的长度len=valueMax-valueMin；如果长度小于1，则返回0；</li>
<li>将数组中的每一个元素装到桶中，桶序号index=(A[i]-valueMin)/len*(n-1)；</li>
<li>将桶中的最大元素保存在bocketMax，最小元素保存在bocketMin；</li>
<li>遍历数组，如果桶为空，则跳过，如果桶不为空，则用当前桶的最小值减去前一个不为空的pre桶的最大值，得到最大区间，将pre桶移动到当前桶位置，继续遍历，区最大区间的最大值即为所求。</li>
</ul>
<p><code>其他方法</code><br>先排序再依次求差值</p>
<ul>
<li>把vector中的元素依次遍历，保存到set中，实现排序；</li>
<li>遍历set，比较相邻的两个元素，得到区间，求区间的最大值。</li>
</ul>
<p><code>代码</code><br><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Gap</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">maxGap</span><span class="params">(<span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt; A, <span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// write code here</span></span><br><span class="line">        <span class="keyword">int</span> valueMax = A[<span class="number">0</span>], valueMin = A[<span class="number">0</span>];</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>; i&lt;n; i++)&#123;</span><br><span class="line">            <span class="keyword">if</span>(A[i]&gt;valueMax)valueMax = A[i];</span><br><span class="line">            <span class="keyword">if</span>(A[i]&lt;valueMin)valueMin = A[i];</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt; bocketMax(n, INT_MIN);</span><br><span class="line">        <span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt; bocketMin(n, INT_MAX);</span><br><span class="line">        <span class="keyword">int</span> len = valueMax - valueMin;</span><br><span class="line">        <span class="keyword">if</span>(len&lt;<span class="number">1</span>)<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;n;i++)&#123;</span><br><span class="line">            <span class="keyword">int</span> index = (<span class="keyword">double</span>)(A[i]-valueMin)/len*(n<span class="number">-1</span>);</span><br><span class="line">            bocketMax[index] = max(A[i], bocketMax[index]);</span><br><span class="line">            bocketMin[index] = min(A[i], bocketMin[index]);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">int</span> ret=<span class="number">0</span>, pre = bocketMax[<span class="number">0</span>];</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">1</span>;i&lt;n;i++)&#123;</span><br><span class="line">            <span class="keyword">if</span>(bocketMin[i]!=INT_MAX)&#123;</span><br><span class="line">                ret = max(ret, bocketMin[i]-pre);</span><br><span class="line">                pre = bocketMax[i];</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> ret;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>如果文章对您有帮助，请随意打赏</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="https://i.loli.net/2018/10/15/5bc436827b4bc.png" alt="刘韬 WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="https://i.loli.net/2018/10/15/5bc4368266e2b.png" alt="刘韬 Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/算法/" rel="tag"># 算法</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/04/18/NCstack/" rel="next" title="[牛客网算法]--栈和队列">
                <i class="fa fa-chevron-left"></i> [牛客网算法]--栈和队列
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/04/25/NClinklist/" rel="prev" title="[牛客网算法]--链表">
                [牛客网算法]--链表 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/avatar.png"
               alt="刘韬" />
          <p class="site-author-name" itemprop="name">刘韬</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">26</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">10</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">12</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/kusole" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.douban.com/people/83381421/" target="_blank" title="豆瓣">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  豆瓣
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.zhihu.com/people/liu-tao-86-26-47/activities" target="_blank" title="知乎">
                  
                    <i class="fa fa-fw fa-facebook"></i>
                  
                  知乎
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/6193724399/profile?topnav=1&wvr=6&is_all=1" target="_blank" title="微博">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  微博
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#排序（一）基础排序算法"><span class="nav-number">1.</span> <span class="nav-text">排序（一）基础排序算法</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#冒泡排序"><span class="nav-number">1.1.</span> <span class="nav-text">冒泡排序</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#选择排序"><span class="nav-number">1.2.</span> <span class="nav-text">选择排序</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#插入排序"><span class="nav-number">1.3.</span> <span class="nav-text">插入排序</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#归并排序"><span class="nav-number">1.4.</span> <span class="nav-text">归并排序</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#快速排序"><span class="nav-number">1.5.</span> <span class="nav-text">快速排序</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#堆排序"><span class="nav-number">1.6.</span> <span class="nav-text">堆排序</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#希尔排序"><span class="nav-number">1.7.</span> <span class="nav-text">希尔排序</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#排序（二）计数排序算法"><span class="nav-number">2.</span> <span class="nav-text">排序（二）计数排序算法</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#计数排序和基数排序"><span class="nav-number">2.1.</span> <span class="nav-text">计数排序和基数排序</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#计数排序"><span class="nav-number">2.1.1.</span> <span class="nav-text">计数排序</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#排序（三）习题"><span class="nav-number">3.</span> <span class="nav-text">排序（三）习题</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#小范围排序"><span class="nav-number">3.1.</span> <span class="nav-text">小范围排序</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#重复值判断"><span class="nav-number">3.2.</span> <span class="nav-text">重复值判断</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#使用hash表方法代码如下"><span class="nav-number">3.2.1.</span> <span class="nav-text">使用hash表方法代码如下</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用堆排序方法代码如下"><span class="nav-number">3.2.2.</span> <span class="nav-text">使用堆排序方法代码如下</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#有序数组合并"><span class="nav-number">3.3.</span> <span class="nav-text">有序数组合并</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#三色排序-荷兰国旗"><span class="nav-number">3.4.</span> <span class="nav-text">三色排序/荷兰国旗</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#有序矩阵查找问题"><span class="nav-number">3.5.</span> <span class="nav-text">有序矩阵查找问题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#最短子数组"><span class="nav-number">3.6.</span> <span class="nav-text">最短子数组</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#相邻两数最大差值"><span class="nav-number">3.7.</span> <span class="nav-text">相邻两数最大差值</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">刘韬</span>

</div>


<div class="Hosted-by">
  由 <a class="theme-link" href="https://pages.github.com/">GitHub Pages</a> 强力驱动
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

<!-- <div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

-->


        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  

  
</div>


        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  






  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/2.1.3/jquery.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fastclick/1.0.6/fastclick.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazyload/1.9.3/jquery.lazyload.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.ui.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  


  




	





  





  





  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>





  

  

  
  


  

</body>
</html>
